//
//  KBRouter.m
//  JavaScriptAndObjectiveC
//
//  Created by 刘红武 on 2018/4/25.
//  Copyright © 2018年 huangyibiao. All rights reserved.
//

#import "KBRouter.h"
@interface KBRouter()
@property(nonatomic,strong)NSMutableDictionary * routeHandles;
@end
@implementation KBRouter
+(instancetype)shard {
    static KBRouter *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!instance) {
            instance = [[KBRouter alloc] init];//启动路由以后在init方法里面启动“”
        }
    });
    
    return instance;
}
-(instancetype)init{
    if (self = [super init]) {
        //添加一个配置
        self.routeHandles = [NSMutableDictionary dictionary];
    }
    return self;
}
-(void)registerHandler:(KBRouteHandler *)handler forRoute:(NSString *)route {
    if (handler && [route length]) {
        self.routeHandles[route] = handler;
    }else {
        NSLog(@"注册时请输入有效参数！");
    }
}

- (void)issueAction:(NSMutableDictionary *)params Controller:(UIViewController *)controll WebView:(UIWebView *)webVi jsContect:(JSContext *)contect {
    
    //校验规则 （符合规则就执行 不符合规则报错处理）
    NSString *service = params[@"service"];//处理器
    NSString *action = params[@"action"];  //响应
    NSString *param = params[@"param"];   //参数
    NSString *successCallback = params[@"successCallback"];  //成功回调
    NSString *errorCallback = params[@"errorCallback"];    //失败回调
    
    BOOL exist = [self.routeHandles.allKeys containsObject:service];
    if (exist) {
        KBRouteHandler *targetHandler = self.routeHandles[service];
        dispatch_async(dispatch_get_main_queue(), ^{
             [targetHandler RealHappenWithParams:params];
        });
         NSLog(@"%@调用成功！",service);
    }else {
         NSLog(@"%@调用失败！",service);
    }
    
    return;
}
@end
